package com.cqrcb.cloud.config.exception;

import com.cqrcb.cloud.entity.api.res.ER;
import com.cqrcb.cloud.entity.api.res.R;
import com.cqrcb.cloud.entity.exception.CustomException;
import com.cqrcb.cloud.entity.exception.ExceptionMember;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 我的异常处理程序
 *
 * @author yangxueyong
 * @date 2021/04/13
 */
@Slf4j
@ControllerAdvice
public class CustomExceptionHandler {

	/**
	 * 异常处理程序
	 *
	 * @param e e
	 * @return {@link R}
	 */
	@ExceptionHandler(value =Exception.class)
	@ResponseBody
	public R exceptionHandler(Exception e){
		log.error("触发异常拦截R->{}", e);
		if(e instanceof CustomException){
			CustomException customException = (CustomException) e;
			if(!customException.isCustom()){
				ExceptionMember exceptionMember = customException.getExceptionMember();
				int code = exceptionMember.getCode();
				String msg = exceptionMember.getMsg();
				return R.fail(code, msg);
			}else{
				return R.fail(customException.getCode(),customException.getExceptionMsg());
			}
		}
       	return R.fail(e.getMessage());
    }

	/**
	 * 异常处理程序
	 *
	 * @param e e
	 * @return {@link ER}
	 */
	@ExceptionHandler(value =Throwable.class)
	@ResponseBody
	public ER exceptionHandler2(Exception e){
		log.error("触发异常拦截ER->{}", e);
		return ER.fail(e.getMessage());
	}
}